package front_user

import (
	"errors"
	"fmt"
	"hft/global"
	"hft/tools"
	"time"

	"github.com/golang-jwt/jwt/v4"
)

type BaseClaims struct {
	ID   int    `json:"id"`
	UUID string `json:"uuid"` //客户的唯一标识
}

type CustomClaims struct {
	BaseClaims
	BufferTime int64
	jwt.StandardClaims
}

// 自定义错误
var (
	TokenExpired     = errors.New("签名过期")
	TokenNotValidYet = errors.New("签名未激活")
	TokenMalformed   = errors.New("签名错误")
	TokenInvalid     = errors.New("签名无法验证")
)

// 成功token
type JWTAuth struct {
	SigningKey []byte
}

// 生成秘钥
func NewJWT() *JWTAuth {
	return &JWTAuth{
		[]byte(global.OC_CONFIG.JWT.SigningKey),
	}
}

// 创建Claims
func (j *JWTAuth) CreateClaims(baseClaims BaseClaims, expire string, buffer string) CustomClaims {
	bf, _ := tools.ParseDuration(expire) //解析buffterTime
	ep, _ := tools.ParseDuration(buffer) //解析expireTime
	fmt.Println(expire, buffer, bf, ep)
	claims := CustomClaims{
		BaseClaims: baseClaims,
		BufferTime: int64(bf / time.Second), // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 1000,    //前面生效时间
			ExpiresAt: time.Now().Add(ep).Unix(),   //签名失效时间
			Issuer:    global.OC_CONFIG.JWT.Issuer, //签发人
		},
	}
	return claims
}

// 生成token
func (j *JWTAuth) CreateToken(claims CustomClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}

// 解析 token
func (j *JWTAuth) ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid
	}
}

// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
func (j *JWTAuth) CreateTokenByOldToken(oldToken string, claims CustomClaims) (string, error) {
	v, err, _ := global.OC_Concurrency_Control.Do("JWT:"+oldToken, func() (interface{}, error) {
		return j.CreateToken(claims)
	})
	return v.(string), err
}
